/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace lcc {

const TAG = "lcc/redis/redis-client.ts";

const redis = require("redis");

/**
 * @zh
 * Redis选项
 */
export interface RedisOptions {
	host?:string;
	port?:number;
	path?:string;
	url?:string;
	string_numbers?:boolean;
	return_buffers?:boolean;
	detect_buffers?:boolean;
	socket_keepalive?:boolean;
	socket_initial_delay?:number;
	no_ready_check?:boolean;
	enable_offline_queue?:boolean;
	retry_unfulfilled_commands?:boolean;
	password?:string;
	user?:string;
	db?:number;
	family?:any;
	disable_resubscribing?:boolean;
	rename_commands?:any;
	tls?:any;
	prefix?:string;
	retry_strategy?:Function;
	connect_timeout?:number;
}

/**
 * @zh
 * Redis命令
 */
export interface RedisCommand {
	/**
	 * @zh
	 * 命令
	 */
	cmd:string ;

	/**
	 * @zh
	 * 参数
	 */
	args:(string|number)[];
}

/**
 * @zh
 * Redis客户端
 */
export class RedisClient extends cocos.event.EventTarget {

	/**
     * @zh
	 * 客户端名称
	 */
	private _name:string = null;

	/**
     * @zh
	 * 客户端选项
	 */
	private _options:RedisOptions = {};

	/**
     * @zh
	 * 客户端实体
	 */
	private _entity:any = null;

	/**
     * @zh
	 * 构造函数
     * 
	 * @param name - 名称
	 * @param type - 类型
	 */
	constructor(name:string, options:RedisOptions){
		super();
		this._name = name;
		this._options = options;
	}
	
	/**
     * @zh
	 * 获得名称
	 */
	public getName(){
		return this._name;
	}
	
	/**
     * @zh
	 * 获得选项
	 */
	public getOptions(){
		return this._options;
	}
	
	/**
     * @zh
	 * 连接Redis<br/>
	 */
	public connect(){
        if(!this._entity){
			this._entity = redis.createClient(this._options);
		}
    }

	/**
     * @zh
	 * 断开Redis<br/>
	 */
	public disconnect(){
        if(this._entity){
			this._entity.quit();
			this._entity = null;
		}
    }
	
	/**
     * @zh
	 * 更新数据库<br/>
     * 如果需要，子类中应重写该函数
     * 
	 * @param dt - 间隔时间
	 */
	public onUpdate(dt:number){}

	/**
	 * @zh
	 * 执行命令
	 * 
	 * @param command 命令名称
	 * @param args 参数列表
	 */
	public execute(command:string|RedisCommand, ...args:(string|number)[]){
		if(this._entity){
			let rc:RedisCommand;
			if(typeof command == "string"){
				rc = {
					cmd : command,
					args : args,
				};  
			}else{
				rc = command;
			}
			let rf:Function = this._entity[rc.cmd.toLocaleLowerCase()];
			if(rf){
				return new Promise<any>((resole)=>{
					rf.call(this._entity, rc.args, (err:any, data:any)=>{
						if(err){
							logMgr.error(TAG, `redis ${this._name} error : ${err}`);
							resole(null);
						}else{
							resole(data);
						}
					});
				});
			}
		}
	}
	
	/**
	 * @zh
	 * 执行多命令
	 * 
	 * @param commands 命令列表
	 */
	public multiExec(...commands:RedisCommand[]){
		if(this._entity){
			const multi = this._entity.multi();
			for(let rc of commands){
				let rf:Function = multi[rc.cmd.toLocaleLowerCase()]; 
				if(rf){
					rf.call(multi, rc.args);
				}
			}
			return new Promise<any>((resole)=>{
				multi.exec(function(err:any, data:any) {
					if(err){
						logMgr.error(TAG, `redis ${this._name} error : ${err}`);
						resole(null);
					}else{
						resole(data);
					}
				});
			});
		}
	}
}

}
